package com.zhenyi.xiaohuoche.admin.web;

import com.jfinal.aop.Clear;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.utils.AESUtils;
import com.utils.AuthUtils;
import com.zhenyi.xhc.core.XHCController;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.URLUtil;

public class AuthController extends XHCController {

	@Clear
	public void index() {
		if (StrKit.notBlank(getPara("state"))) {
			String state = URLUtil.decode(getPara("state"));
			setAttr("URL", state);
		}
		// if (StrKit.notBlank(AuthUtils.getTokenUid(this))) {
		// redirect("");
		// }
		String key = RandomUtil.randomString(16);
		setAttr("key", key);
		setSessionAttr("key", key);
		render("/xhc/admin/auth/index.html");
	}

	private final String VERIFY_ACCOUNT = PropKit.get("XHC_ADMIN_ACCOUNT", "lets");
	private final String VERIFY_PASSWORD = PropKit.get("XHC_ADMIN_PASSWORD", "lets");

	@Clear
	@Override
	public void submit() {
		String account = getPara("account");
		if (!VERIFY_ACCOUNT.equals(account)) {
			renderFailure("账号/密码错误 错误代码:100501");
			return;
		}

		String password = getPara("password");
		try {
			String key = getSessionAttr("key");
			password = AESUtils.decrypt(key, password);
			if (!VERIFY_PASSWORD.equals(password)) {
				renderFailure("账号/密码错误 错误代码:100501");
				return;
			}
			AuthUtils.login("CHUCHU", this);
			renderSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			renderFailure("账号/密码错误 错误代码:100500");
			return;
		}

	}

	@Clear
	public void auth() {
		// String account = getPara("account");
		// String password = getPara("password");
		// if (!StrKit.notBlank(account, password)) {
		// renderFailure();
		// return;
		// }
		// String token = "xhc" + DateUtil.now();
		// String de = AESUtils.decrypt(AES_KEY, password);
		// String acc = PropKit.get("acc", "admin");
		// String pwd = PropKit.get("pwd", "admin");
		// if (!acc.equals(account) || !pwd.equals(de)) {
		// renderFailure();
		// return;
		// }
		// token = DigestUtil.md5Hex(token);
		// renderResult(AuthUtils.login(token, this));
		// new Thread(new Runnable() {
		// public void run() {
		// ThreadUtil.safeSleep(60000);
		// logout();
		// }
		// }).start();
		renderSuccess();
	}

	public void logout() {
		AuthUtils.logout(this);
		renderSuccess();
	}

}
